/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.cluster.mom;

import com.google.common.base.Preconditions;

import edu.byu.nlp.cluster.AnnealedEMAble;
import edu.byu.nlp.cluster.Dataset;
import edu.byu.nlp.cluster.ProbabilisticModel;
import edu.byu.nlp.cluster.em.Annealable;
import edu.byu.nlp.cluster.em.ClusteringAndPredictiveModels;
import edu.byu.nlp.cluster.em.Expectable;

/**
 * @author rah67
 *
 */
public class EMEMAble implements AnnealedEMAble<MoMParameters> {

	private final double alpha;
	private final double beta;
	
	public EMEMAble(double alpha, double beta) {
		Preconditions.checkArgument(alpha > 1.0, "alpha value of %s is not greater than 1.0", alpha);
		Preconditions.checkArgument(beta > 1.0, "beta value of %s is not greater than 1.0", beta);
		
		this.alpha = alpha;
		this.beta = beta;
	}

	/** {@inheritDoc} */
	@Override
	public Expectable<MoMParameters> newExpectableFor(Dataset data, int numClusters) {
		// Cache the counts of the labeled data
		// The minus one is due to the fact that the mode of a (posterior) Dirichlet distribution is (alpha - 1 + c_k)
		double[] alphaMinusOneAndObservedCounts =
				MixtureOfMultinomialsUtil.posteriorAlpha(data, alpha - 1, numClusters);
		double[][] betaMinusOneAndObservedCounts = MixtureOfMultinomialsUtil.posteriorBeta(data, beta - 1, numClusters);
		return new EMExpectable(alpha, beta, alphaMinusOneAndObservedCounts, betaMinusOneAndObservedCounts);
	}

	/** {@inheritDoc} */
	@Override
	public ClusteringAndPredictiveModels newModelsFrom(MoMParameters parameters) {
		// no difference between predictive and clustering model
		ProbabilisticModel model = MixtureOfMultinomialsModel.newWithParameters(parameters, false);
		return ClusteringAndPredictiveModels.fromSingleModel(model);
	}

	/** {@inheritDoc} */
	@Override
	public Annealable<MoMParameters> newAnnealableFor(Dataset data, int numClusters) {
		// Cache the counts of the labeled data
		// The minus one is due to the fact that the mode of a (posterior) Dirichlet distribution is (alpha - 1 + c_k)
		double[] alphaMinusOneAndObservedCounts =
				MixtureOfMultinomialsUtil.posteriorAlpha(data, alpha - 1, numClusters);
		double[][] betaMinusOneAndObservedCounts = MixtureOfMultinomialsUtil.posteriorBeta(data, beta - 1, numClusters);
		return new EMAnnealable(alpha, beta, alphaMinusOneAndObservedCounts, betaMinusOneAndObservedCounts);
	}

}
